package com.draven.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.draven.mall.entity.Rider;
import com.draven.mall.mapper.RiderMapper;
import com.draven.mall.service.RiderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * 骑手服务实现类
 */
@Service
public class RiderServiceImpl extends ServiceImpl<RiderMapper, Rider> implements RiderService {

    @Override
    public Rider login(String username, String password) {
        LambdaQueryWrapper<Rider> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Rider::getUsername, username)
                .eq(Rider::getPassword, password)
                .eq(Rider::getStatus, 1); // 状态正常的骑手
        return getOne(queryWrapper);
    }

    @Override
    public Rider register(Rider rider) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<Rider> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Rider::getUsername, rider.getUsername());
        if (count(queryWrapper) > 0) {
            return null;
        }

        // 检查手机号是否已存在
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Rider::getPhone, rider.getPhone());
        if (count(queryWrapper) > 0) {
            return null;
        }

        // 设置默认字段
        rider.setCreatedTime(new Date());
        rider.setUpdatedTime(new Date());
        rider.setStatus(0); // 待审核状态
        rider.setWorkingStatus(0); // 休息中

        // 保存骑手信息
        save(rider);
        return rider;
    }

    @Override
    public Rider getRiderByUsername(String username) {
        if (username == null || username.trim().isEmpty()) {
            return null;
        }
        
        // 根据用户名查询骑手信息
        LambdaQueryWrapper<Rider> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Rider::getUsername, username);
        
        return getOne(queryWrapper);
    }

    @Override
    @Transactional
    public boolean updateGrabOrderStatus(Long riderId, Integer status) {
        if (riderId == null || status == null || (status != 0 && status != 1)) {
            return false;
        }
        
        // 更新骑手抢单状态
        LambdaUpdateWrapper<Rider> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Rider::getId, riderId)
                    .set(Rider::getGrabOrderStatus, status)
                    .set(Rider::getUpdatedTime, new Date());
        
        return update(updateWrapper);
    }

    @Override
    public List<Rider> getAvailableRiders() {
        // 查询所有状态正常(status=1)且开启抢单(grabOrderStatus=1)的骑手
        LambdaQueryWrapper<Rider> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Rider::getStatus, 1)
                   .eq(Rider::getGrabOrderStatus, 1);
        
        return list(queryWrapper);
    }

    /**
     * 获取骑手评价列表
     */
    @Override
    public Map<String, Object> getRiderRatings(Long riderId, Integer page, Integer size, String rating) {
        // 默认分页参数
        page = (page == null || page < 1) ? 1 : page;
        size = (size == null || size < 1) ? 10 : size;
        
        // 创建分页对象
        Page<Map<String, Object>> pageParam = new Page<>(page, size);
        
        // 查询评价列表
        IPage<Map<String, Object>> pageResult = baseMapper.selectRiderRatings(pageParam, riderId, rating);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("pages", pageResult.getPages());
        result.put("current", pageResult.getCurrent());
        result.put("size", pageResult.getSize());
        
        // 查询评价统计信息
        Map<String, Object> statistics = new HashMap<>();
        
        try {
            // 查询各星级评价数量
            Map<String, Long> ratingsCount = baseMapper.countRiderRatingsByScore(riderId);
            
            // 如果结果为空，创建默认的空Map
            if (ratingsCount == null) {
                ratingsCount = new HashMap<>();
            }
            
            long excellentCount = 
                (ratingsCount.getOrDefault("5", 0L) + ratingsCount.getOrDefault("4", 0L));
            long goodCount = ratingsCount.getOrDefault("3", 0L);
            long badCount = 
                (ratingsCount.getOrDefault("2", 0L) + ratingsCount.getOrDefault("1", 0L));
            
            statistics.put("excellentCount", excellentCount);
            statistics.put("goodCount", goodCount);
            statistics.put("badCount", badCount);
            statistics.put("ratingDetails", ratingsCount);
        } catch (Exception e) {
            // 出现异常时，使用默认的统计数据
            statistics.put("excellentCount", 0L);
            statistics.put("goodCount", 0L);
            statistics.put("badCount", 0L);
            statistics.put("ratingDetails", new HashMap<String, Long>());
        }
        
        result.put("statistics", statistics);
        
        return result;
    }
}
